package com.raylu.realtime.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.java.tuple.Tuple2;
import redis.clients.jedis.Jedis;
import java.util.List;

/**
 * Description:
 * <p>
 * Create by lucienoz on 2021/12/30.
 * Copyright © 2021 lucienoz. All rights reserved.
 */

public class DimUtil {
    public static JSONObject qurayTableByPkNoCache(String table_name, Tuple2<String, Object>... conditions) {
        StringBuilder querySql = new StringBuilder();
        querySql.append("select * from " + table_name + "\n");
        querySql.append(" where 1=1\n");
        for (Tuple2<String, Object> condition : conditions) {
            querySql.append(" and " + condition.f0 + " = " + (condition.f1 instanceof String ? "'" + condition.f1 + "'\n" : condition.f1));
        }
        List<JSONObject> jsonObjects = PhoenixUtil.selectQuery(querySql.toString(), JSONObject.class);
        if (jsonObjects != null && jsonObjects.size() > 0) {
            return jsonObjects.get(0);
        }
        return null;
    }

    public static JSONObject qurayTableByPkWithCache(String table_name, Tuple2<String, Object>... conditions) {
        //TODO 1. 拼接redis key
        StringBuilder keyStr = new StringBuilder("DIM:" + table_name.toUpperCase());
        for (Tuple2<String, Object> condition : conditions) {
            keyStr.append(":" + condition.f0.toUpperCase() + ":" + condition.f1.toString());
        }

        //TODO 2. 获取jedis对象
        Jedis jedis = RedisUtil.getJedis();
        jedis.select(6);
        String jsonStr = jedis.get(keyStr.toString());
        JSONObject jsonObject = null;
        if (jsonStr == null || jsonStr.length() == 0) {
            System.out.println("缓存中不存在，在phoenix进行查询");
            jsonObject = qurayTableByPkNoCache(table_name, conditions);
            if (jsonObject != null && jsonObject.size() > 0) {
                jedis.setex(keyStr.toString(), 24 * 3600, jsonObject.toJSONString());

            }
        } else {
            jsonObject = JSONObject.parseObject(jsonStr);
            jedis.expire(keyStr.toString(),24*3600);
        }
        if (jedis != null) {
            jedis.close();
        }
        return jsonObject;
    }


    public static void main(String[] args) {
        qurayTableByPkWithCache("GMALL2021.DIM_USER_INFO", Tuple2.of("id", "991"));
        long start = System.currentTimeMillis();
        JSONObject id = qurayTableByPkWithCache("GMALL2021.DIM_USER_INFO", Tuple2.of("id", "992"));
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        System.out.println(id);

    }


}
